package com.storage.joyce.storageapp.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.storage.joyce.storageapp.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * Created by lenovo on 2015/3/13.
 */
public class Tools {

    private static String Tag="aaaaaa";
    private static Toast toast = null;

    private  Handler mHandler = new Handler(MyApplication.context.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (toast != null) {
                        toast.cancel();
                        toast = Toast.makeText(MyApplication.context, msg.obj + "", Toast.LENGTH_SHORT);
                    } else {
                        toast = Toast.makeText(MyApplication.context, msg.obj + "", Toast.LENGTH_SHORT);
                    }
                    toast.show();
                    break;
                case 2:
                    Toast.makeText(MyApplication.context, msg.obj + "", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public static void logi(Object message){
        Log.i(Tag, message + "");
    }

    public static void loge(Object message){
        Log.e(Tag, message + "");
    }
    public static void toast(Object message){
        Message msg=new Handler().obtainMessage();
        msg.what=1;
        msg.obj=message;
        new Handler().sendMessage(msg);
    }
    /**
     * Activity的退出方法，如果内存小于10％，则清内存退出（System.exit(0)）
     */
    public static void exit(Activity activity){
        if (getUsedPercentValue(activity)>10){
            activity.finish();
        }else {
            System.exit(0);
        }
    }

    /**
     * 传入需要推送的消息消息，推送到消息栏
     * @param id 需要推送的消息消息的id（标示符）
     * @param title 需要推送的消息消息的标题
     * @param message 需要推送的消息消息
     * @param intent 需要推送的消息消息需要跳转的intent
     */
    public static void showNotification(Context context,int id,String title,String message,Intent intent) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(ns);
        int icon = R.mipmap.ic_launcher;//消息栏LOGO
        CharSequence tickerText = message;//消息推送时显示的内容（仅显示一次）
        long when = System.currentTimeMillis();//消息栏时间
        Notification notification = new Notification(icon, tickerText,
                when);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        Context uiContext = context.getApplicationContext();
        PendingIntent contentIntent = PendingIntent.getActivity
                (uiContext, 0, intent, 0);//点击消息后需要转跳的页面
        notification.setLatestEventInfo(uiContext, title,
                message, contentIntent);//消息栏标题,消息栏正文内容
        mNotificationManager.notify(id, notification);
    }


    private static int getUsedPercentValue(Context context) {
        String dir = "/proc/meminfo";
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
            am.getMemoryInfo(mi);
            FileReader fr = new FileReader(dir);
            BufferedReader br = new BufferedReader(fr, 2048);
            String memoryLine = br.readLine();
            String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
            br.close();
            long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""))/1024;
            long availableSize = mi.availMem/1024/1024;// 将获取的内存大小规格化
            return (int)(availableSize*100/totalMemorySize) ;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
    /**
     * 判断当前网络是否连接
     */
    public static boolean networkTest(Context context) {

        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }

        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }

        return true;
    }
    /**
     * 获取友盟推送时的消息
     */
    public static Map<String,String> getUMengData(Intent intent){
        Map<String,String> map = null;
        Bundle bun = intent.getExtras();
        if (bun != null)
        {
            map=new HashMap<>();
            Set<String> keySet = bun.keySet();
            for (String key : keySet) {
                map.put(key,bun.getString(key));
            }
        }
        return map;
    }
    /**
     * 获取友盟推送时的json消息
     */
    public static Map<String,Object> getpushData(Intent intent){
        Map<String,String> map=new HashMap<>();
        Bundle bun = intent.getExtras();
        if (bun != null)
        {
           ;
            Set<String> keySet = bun.keySet();
            for (String key : keySet) {
                map.put(key,bun.getString(key));
            }
        }
        Map<String,Object> pushMap=null;
        //if (null!=map.get(OtherType.pushData))pushMap=CommonJSONParser.parse(map.get(OtherType.pushData));
        return pushMap;
    }
    /**
     * 获取文件夹大小
     */
    public static long getTotalSizeOfFilesInDir(final File file) {
        if (file.isFile())
            return file.length();
        final File[] children = file.listFiles();
        long total = 0;
        if (children != null)
            for (final File child : children)
                total += getTotalSizeOfFilesInDir(child);
        return total;
    }
    /**
     * 递归删除文件和文件夹
     * @param file    要删除的根目录
     */
    public static void RecursionDeleteFile(File file){
        if(file.isFile()){
            file.delete();
            return;
        }
        if(file.isDirectory()){
            File[] childFile = file.listFiles();
            if(childFile == null || childFile.length == 0){
                file.delete();
                return;
            }
            for(File f : childFile){
                RecursionDeleteFile(f);
            }
            file.delete();
        }
    }
    /*
      * Java文件操作 获取不带扩展名的文件名
     *
      *  Created on: 2011-8-2
      *      Author: blueeagle
      */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;

    }


}
